package com.dudu.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dudu.dto.ResultDto;
import com.dudu.pojo.Driver;
import com.dudu.service.DriverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/driver")
public class DriverController {
    @Autowired
    private DriverService driverService;

    @PostMapping("/updateDriverStatus")
    public ResultDto updateDriverStatus(@RequestBody Driver driver) {
        driverService.update(new UpdateWrapper<Driver>()
                .set("driver_status", driver.getDriverStatus())
                .eq("driver_id", driver.getDriverId()));
        return ResultDto.success("更新司机状态成功！",null);
    }


    /**
     * 用户注册方法
     *
     * @param driver 包含用户注册信息的User对象
     * @return 注册结果的消息
     */
    @PostMapping("/register") // 处理POST请求，路径为 /api/user/register
    public ResultDto register(@RequestBody Driver driver) { // 从请求体中获取User对象
        QueryWrapper<Driver> wrapper = new QueryWrapper<Driver>()
                .eq("divername",driver.getDriverName());
        Driver isExisUser = driverService.getOne(wrapper);
        // 保存新用户
        if ( isExisUser != null){
            StpUtil.login(isExisUser.getDriverId());

            return ResultDto.error("用户已存在",null);
        }
        driverService.saveOrUpdate(driver);
//        userService.saveUser(user);
        return ResultDto.success("注册成功",null);
    }
    /**
     * 用户登录方法
     *
     * @param driver 包含用户登录信息的User对象
     * @return 登录结果的消息
     */
    @PostMapping("/login") // 处理POST请求，路径为 /api/user/login
    public SaResult login(@RequestBody Driver driver) { // 从请求体中获取User对象
        System.out.println("driver_acc: " + driver.getDriverAcc());
        System.out.println("driver_pwd: " + driver.getDriverPwd());
        // 验证用户名和密码
        QueryWrapper<Driver> wrapper = new QueryWrapper<Driver>()
                .eq("driver_acc",driver.getDriverAcc())
                .eq("driver_pwd",driver.getDriverPwd());
        driver = driverService.getOne(wrapper);

        if (driver !=null){
            StpUtil.login(driver.getDriverId());
            return SaResult.data(driver);
        }
        return SaResult.error("登录失败");
    }

    @GetMapping("outLogin/{driver}")
    public SaResult outLogin(@PathVariable Integer driverId){
        try{
            if (driverId!=null){
                StpUtil.logout(driverId);
                return SaResult.ok("退出成功");
            }else {
                return SaResult.error("用户ID为空！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return SaResult.error("系统出错请联系管理员").setData(e.getMessage());
        }
    }
}
